package com.tancw.cloud.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.tancw.cloud.common.Result;
import com.tancw.cloud.user.entity.User;
import com.tancw.cloud.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    @SentinelResource(value = "getUserById")
    public Result<User> getUserById(@PathVariable Long id) {
        log.info("查询用户: {}", id);
        User user = userService.getById(id);
        return Result.success(user);
    }

    @GetMapping("/username/{username}")
    @SentinelResource(value = "getUserByUsername")
    public Result<User> getUserByUsername(@PathVariable String username) {
        log.info("根据用户名查询用户: {}", username);
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    @PostMapping
    public Result<Void> createUser(@RequestBody User user) {
        log.info("创建用户: {}", user.getUsername());
        userService.save(user);
        return Result.success();
    }

    @PutMapping
    public Result<Void> updateUser(@RequestBody User user) {
        log.info("更新用户: {}", user.getId());
        userService.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        log.info("删除用户: {}", id);
        userService.removeById(id);
        return Result.success();
    }
}
